<link rel="stylesheet" href="/layui/css/layui.css">
<script src="/layui/layui.js"></script>
<script>
    //Demo
    layui.use(['form', 'layer', 'jquery', 'element'], function () {
        var form = layui.form;
        var element = layui.element;
        var layer = layui.layer;
        var $ = layui.$;
        var token = '{{csrf_token()}}'
        var id = {{$id}};
        var material_id = {};
        var old_number = {};

        // 验证是否修改了材料
        function checkMaterial(material_id, number, data)
        {
            //console.log(material_id, number, data);
            //console.log(material_id.length, data[0].length);
            if(material_id.length == data[0].length){
                // 验证material_id
                for(var i in material_id){
                    if(material_id[i] !== data[0][i]['material_id']){
                        console.log('material_id');
                        return false;
                    }
                }
                // 验证number
                for(var i in number){
                    if(number[i] !== data[1][i]['number']){
                        console.log(number[i]);
                        return false;
                    }
                }
            } else {
                return false;
            }
            return true;
        }
        //监听提交
        form.on('submit(formDemo)', function (data) {
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            //layer.msg(JSON.stringify(data.field));
            // 组装提交数据
            //console.log(data.field);
            var datas = [];
            var material = [];
            $('.materials-td').find('dd.layui-this').each(function () {
                var item = {};
                item.material_id = $(this).attr('lay-value');
                material.push(item);
            });
            var number = [];
            $('.number-td').find('input').each(function(){
                var item = {};
                item.number = $(this).val();
                number.push(item);
            });
            var price = [];
            $('.price-td').find('input').each(function () {
                var item = {};
                item.price = $(this).val();
                price.push(item);
            });
            var linePrice = [];
            $('.linePrice-td').find('input').each(function () {
                var item = {};
                item.linePrice = $(this).val();
                linePrice.push(item);
            });
            var data = [material, number];

            // 验证表单是否更改过
            $res = checkMaterial(material_id, old_number, data);
            // console.log('res', $res);
            if($res == false){
                layer.open({
                   titel:'提示',
                   content:'检测到表单发生了修改，继续提交会使当前sku库存清零',
                   yes:function(layers){
                        $.post('{{route('sharp-goods.update', ['sharp_good' => $id])}}', {
                            id:id,
                            materials:material,
                            numbers:number,
                            price:price,
                            linePrice:linePrice,
                            _token:token,
                            _method: 'PUT',
                        }, function(data){
                            if(data.code == 1){
                                layer.open({
                                    title:'提示',
                                    content:data.msg,
                                    yes:function (layers) {
                                        layer.close(layers);
                                        parent.layer.close(index); //再执行关闭
                                    }
                                });
                            }
                        });
                        layer.close(layers);
                   }
                });
            } else {
                 $.post('{{route('sharp-goods.update', ['sharp_good' => $id])}}', {
                    id:id,
                    materials:material,
                    numbers:number,
                    price:price,
                    linePrice:linePrice,
                    _token:token,
                    _method: 'PUT',
                }, function(data){
                    if(data.code == 1){
                        layer.open({
                            title:'提示',
                            content:data.msg,
                            yes:function (layers) {
                                layer.close(layers);
                                parent.layer.close(index); //再执行关闭
                            }
                        });
                    }
                });
            }
            //console.log(material, number);
            return false;
        });

        var goodsClassify = JSON.parse('{!! json_encode($goodsClassify) !!}');

        // 新增行
        $(document).on('click', 'span.add', function () {
            row();
        });
        // 减少行
        // 减少行
        $(document).on('click', 'span.reduce', function () {
            var checked = $('.layui-form-checked');
            var goods_sku_id = 0;
            var material_ids = [];
            var ids = [];
            checked.each(function() {
                var id = $(this).parent().siblings('.materials-td').find('dl').find('dd.layui-this').attr('lay-value');
                material_ids.push(id);
            });
            if(checked.length <= 0) {
                layer.msg('没有选择任何一行!');
            } else {
                checked.each(function () {
                    $(this).parent().parent().remove();
                });
            }
        });

        // 组装新的行
        function row() {
            var materials = [];
            // 计算一共多少行
            var length = $('.materials-row').children('tr').length;

            var html = '<tr>';
            html += checkBox(length);
            html += classifySelect(goodsClassify, length);
            html += material(materials, length);
            html += numbers(length);
            html += price(length);
            html += linePrice(length);
            html += '</tr>';
            $('.materials-row').append(html);
            // 更新渲染
            form.render();
        }
        // 组装复选框
        function checkBox(length) {
            var html = '';

            html += '<td class="checkbox">';
            html += '<input type="checkbox" name="" title="" lay-skin="primary">';
            html += '</td>';

            return html;
        }

        // 组装材料分类单选框元素
        function classifySelect(materialClassify, length) {
            var html = '<td class="materialClassify-td">';
            html += '<select lay-filter="materialClassify" lay-search class="layui-input layui-table-input" name="materialClassify-'+length+'" lay-verify="required">';
            html += '<option value=""></option>';

            for(var i in materialClassify){
                html += '<option value='+ i +'>' + materialClassify[i] + '</option>';
            }

            html += '</select>';
            html += '</td>'
            return html;
        }

        // 组装材料单选框元素
        function material(materials, length) {

            var html = '<td class="materials-td">';
            html += '<select lay-filter="materials" lay-search class="layui-input layui-table-input" name="materials-'+ length +'" lay-verify="required">';
            html += '<option>请选择</option>';
            for(var i in materials){
            html += '<option value="'+ materials[i].id +'">'+materials[i].name+'</option>';
            }
            html += '</select>';
            html += '</td>'
            return html;
        }

        // 组装数量输入框
        function numbers(length) {
            var html = '<td class="number-td">';
            html += '<input lay-filter="number" type="text" name="number-'+ length +'" required lay-verify="required|number" placeholder="请输入数量" autocomplete="off" class="layui-input layui-table-input">';
            html += '</td>';
            return html;
        }
        // 组装秒杀价输入框
        function price(length) {
            var html = '<td class="price-td">';
            html += '<input lay-filter="price" type="text" name="price-'+ length +'" required lay-verify="required|number" placeholder="请输入秒杀价格" autocomplete="off" class="layui-input layui-table-input">';
            html += '</td>';
            return html;
        }
        // 组装划线价输入框
        function linePrice(length) {
            var html = '<td class="linePrice-td">';
            html += '<input lay-filter="linePrice" type="text" name="linePrice-'+ length +'" required lay-verify="required|number" placeholder="请输入划线价格" autocomplete="off" class="layui-input layui-table-input">';
            html += '</td>';
            return html;
        }
        // 记录初始材料与数量
        function initMaterials()
        {
            var id = [], num = [];
            $('td.materials-td').find('dd.layui-this').each(function () {
                id.push($(this).attr('lay-value'));
            });
            $('input[lay-filter=number]').each(function () {
                num.push($(this).val());
            });

            material_id = JSON.parse(JSON.stringify(id));
            old_number = JSON.parse(JSON.stringify(num));
        }
        initMaterials();


        ///***选择材料分类的事件***///
        form.on('select(materialClassify)', function(data){
          // console.log(data.elem); //得到select原始DOM对象
          // console.log(data.value); //得到被选中的值
          // console.log(data.othis); //得到美化后的DOM对象
          var that = data.othis;
          var material_id = [];
          var data1 = $('.materials-td').find('dd.layui-this').each(function () {
            material_id.push($(this).attr('lay-value'));
          });

          $.post('{{route('getNoSkuGoods')}}', {
              no_sku:1,
              material_id:material_id,
              id:data.value,
              goods_classify_id:data.value,
              _token:'{{csrf_token()}}'
          }, function (data) {
                if(data.code == 1){
                    // 更新当前列材料数据
                    that.parent().siblings('.materials-td').remove();
                    that.parent().siblings('.number-td').before(material(data.data));
                    form.render();
                }
          });
        });

        // 全选按钮
        form.on('checkbox(check-all)', function (data) {
            var checked = data.elem.checked;
            if (checked == true) {
                $('.layui-form-checkbox').addClass('layui-form-checked');
            } else {
                $('.layui-form-checkbox').removeClass('layui-form-checked');
            }
        });
    });

    // 传值给父页面
    //var txt = '我是子界面主动传值给父界面的数值';
    //parent.layui.GetChildValue(txt); //GetValue是父界面的Js 方法
</script>
<form class="layui-form" action="" style="height: 500px">

    <table class="layui-table">
        <thead>
        <tr>
            <th><input lay-filter="check-all" type="checkbox" class="check-all" name="" title="" lay-skin="primary"></th>
            <th>商品分类</th>
            <th>名称</th>
            <th>所需数量</th>
            <th>秒杀价</th>
            <th>划线价</th>
        </tr>
        </thead>
        <tbody class="materials-row">
@if(isset($default))
        @foreach($default as $value)
            <tr class="index-{{$loop->index}}">
                <td class="checkbox">
                    <input type="checkbox" class="index-{{$loop->index}}" name="" title="" lay-skin="primary">
                </td>
                <td class="materialClassify-td">
                    <select lay-filter='materialClassify' lay-search class="layui-input layui-table-input"
                            name="materialClassify-{{$loop->index}}" lay-verify="required">
                        <option value=""></option>
                        @if(isset($goodsClassify))
                            @foreach($goodsClassify as $k => $v)
                                @if($value->goods->classify[0]->id == $k)
                                    <option selected value="{{$k}}">{{$v}}</option>
                                    @else
                                    <option value="{{$k}}">{{$v}}</option>
                                @endif
                            @endforeach
                        @endif
                    </select>
                </td>
                <td class="materials-td">
                    <select lay-filter='materials' lay-search class="layui-input layui-table-input" name="goods-{{$loop->index}}"
                            lay-verify="required">
                        <option value=""></option>
                        @foreach($goods as $k => $v)
                            @if($value->goods_id == $v->id)
                                <option selected value="{{$v->id}}">{{$v->name}}</option>
                            @endif
                        @endforeach
                    </select>
                </td>
                <td class="number-td">
                    <input lay-filter='stock' type="text" name="stock-{{$loop->index}}" required lay-verify="required|number"
                           placeholder="请输入数量" autocomplete="off"
                           class="layui-input layui-table-input" value="{{$value->stock}}">
                </td>
                <td class="price-td">
                    <input lay-filter='price' type="text" name="price-{{$loop->index}}" required lay-verify="required|number"
                           placeholder="请输入秒杀价" autocomplete="off"
                           class="layui-input layui-table-input" value="{{$value->price}}">
                </td>
                <td class="linePrice-td">
                    <input lay-filter='linePrice' type="text" name="line_price-{{$loop->index}}" required lay-verify="required|number"
                           placeholder="请输入划线价" autocomplete="off"
                           class="layui-input layui-table-input" value="{{$value->line_price}}">
                </td>
            </tr>
        @endforeach
@endif

        </tbody>

    </table>


    <div class="layui-form-item">
        <div class="layui-row">
            <div class="layui-col-md12 layui-col-md-offset8">
                <div class="layui-input-block layui-btn-container">
                    <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    <span class="layui-btn layui-btn-primary add">新增行</span>
                    <span class="layui-btn layui-btn-primary reduce">减少行</span>
                </div>
            </div>
{{--            <div class="layui-col-md6">--}}
{{--                <div class="layui-btn-container">--}}
{{--                    <span class="layui-btn layui-btn-primary add">新增行</span>--}}
{{--                    <span class="layui-btn layui-btn-primary reduce">减少行</span>--}}
{{--                </div>--}}
{{--            </div>--}}
        </div>
    </div>
</form>